import altair as alt
import pandas as pd
import geopandas as gpd
df = pd.read_csv('population_trends.csv')
df = df[df.region != 'Ukraine']
df.head()
| region | year | rate | |
|---|---|---|---|
| 31 | Crimea | 1989 | 3.9 |
| 32 | Crimea | 1990 | 2.5 |
| 33 | Crimea | 1991 | 0.9 |
| 34 | Crimea | 1992 | -0.7 |
| 35 | Crimea | 1993 | -2.7 |
ua = gpd.read_file('ukraine.json')
df_2019 = df[df["year"] == 2019]
df_2019.head()
| region | year | rate | |
|---|---|---|---|
| 61 | Crimea | 2019 | NaN |
| 92 | Vinnytsya | 2019 | -7.9 |
| 123 | Volyn | 2019 | -2.8 |
| 154 | Dnipropetrovs'k | 2019 | -8.9 |
| 185 | Donets'k | 2019 | NaN |
select_city = alt.selection_single(on = 'mouseover', nearest = False, empty = 'none')
alt.Chart(ua).transform_lookup(
lookup = 'NAME_1',
from_ = alt.LookupData(data=df_2019,
key='region',
fields=['region', 'rate'])
).mark_geoshape().encode(
strokeWidth=alt.condition(select_city, alt.value(3), alt.value(1)),
stroke=alt.condition(select_city, alt.value('red'), alt.value('black')),
color = alt.Color('rate:O'),
tooltip = [alt.Tooltip('rate:O'), alt.Tooltip('region:N')]
).add_selection(select_city).properties(width = 900, height = 400)
select_city = alt.selection_single(on = 'mouseover', nearest = False, fields = ['region'], empty = 'all')
select_city_empty = alt.selection_single(on = 'mouseover', nearest = False, empty = 'none')
first = alt.Chart(ua).transform_lookup(
lookup = 'NAME_1',
from_ = alt.LookupData(data=df_2019,
key='region',
fields=['region', 'rate'])
).mark_geoshape().encode(
strokeWidth=alt.condition(select_city, alt.value(3), alt.value(1)),
stroke=alt.condition(select_city_empty, alt.value('red'), alt.value('black')),
opacity=alt.condition(
select_city,
alt.value(1),
alt.value(0.1)),
color = alt.Color('rate:O'),
tooltip = [alt.Tooltip('rate:O'), alt.Tooltip('region:N')]
).add_selection(select_city).add_selection(select_city_empty)
first.properties(width = 900, height = 600)
second = alt.Chart(df).mark_line().encode(
x = alt.X('year:Q'),
y = alt.Y('rate:Q'),
detail = alt.Detail('region:N'),
opacity=alt.condition(
select_city,
alt.value(1),
alt.value(0.1)),
tooltip = [alt.Tooltip('rate:O'), alt.Tooltip('region:N')]
).add_selection(select_city)
second.properties(width = 900, height = 600)
alt.vconcat(alt.hconcat(first.properties(width = 400, height = 300), second.properties(width = 400, height = 300))).configure_concat(spacing = 0)